define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 修改编辑窗口的大小
            $(".btn-edit").data("area", ["50%", "60%"]);
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'coupon/mt/index' + location.search,
                    add_url: 'coupon/mt/add',
                    edit_url: 'coupon/mt/edit',
                    del_url: 'coupon/mt/del',
                    multi_url: 'coupon/mt/multi',
                    import_url: 'coupon/mt/import',
                    table: 'shop_meituan',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                singleSelect: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'shop.name', title: __('Shop.name'), operate: 'LIKE'},
                        {
                            field: 'room_name',
                            title: __('包厢/台桌名称'),
                            operate: false,
                            align: 'left',
                            // formatter: Table.api.formatter.label,
                            formatter: function (value, row, index, field) {
                                if (value == null) {
                                    return "";
                                }
                                return "<span style='display: block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;' title='" + value + "'>" + value + "</span>";
                            },
                            cellStyle: function (value, row, index, field) {
                                return {
                                    css: {
                                        "white-space": "nowrap",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width": "200px"
                                    }
                                };
                            },
                        },
                        {
                            field: 'title',
                            title: __('Title'),
                            operate: 'LIKE',
                            align: 'left',
                            formatter: function (value, row, index, field) {
                                if (value == null) {
                                    return "";
                                }
                                return "<span style='display: block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;' title='" + row.title + "'>" + value + "</span>";
                            },
                            cellStyle: function (value, row, index, field) {
                                return {
                                    css: {
                                        "white-space": "nowrap",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width": "200px"
                                    }
                                };
                            }
                        },

                        {field: 'hour', title: __('Hour'), operate: false, sortable: true},
                        {field: 'use_time', title: __('Use_time'), operate: false},
                        {field: 'week', title: __('Week'), operate: false},
                        {
                            field: 'type',
                            title: __('Type'),
                            operate: 'LIKE',
                            searchList: {"qp": __('棋牌'), "tq": __('台球')},
                            formatter: function (value) {
                                if (value === 'qp') {
                                    return '棋牌';
                                } else if (value === 'tq') {
                                    return '台球';
                                } else {
                                    return '其他';
                                }
                            }
                        },
                        {field: 'price', title: __('Price'), operate: false},
                        {field: 'marketprice', title: __('Marketprice'), operate: false},
                        {field: 'sale_status', title: __('Sale_status'), operate: false},
                        {
                            field: 'receipt_begin_date',
                            title: __('Receipt_begin_date'),
                            operate: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'receipt_end_date',
                            title: __('Receipt_end_date'),
                            operate: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            //打开同步窗口
            $(document).on("click", ".btn-mtSync", function () {
                Fast.api.open('coupon/mt/sync', '一键同步美团券');
            });

            table.on('post-body.bs.table', function () {
                $(".btn-editone").data("area", ["50%", "60%"]);
                $(".btn-addone").data("area", ["50%", "60%"]);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {

            //同步包厢
            $("#c-room_id").data("params", function () {
                return {custom: {shop_id: $("#c-shop_id").val()}};
            });

            //同步台桌
            $("#c-table_id").data("params", function () {
                return {custom: {shop_id: $("#c-shop_id").val()}};
            });

            var newVal = $("#c-type").val();
            console.log(newVal);
            if (newVal === 'qp') {
                $("#c-table_id").val('');
                $('#room').show();
                $('#table').hide();
            }
            if (newVal === 'tq') {
                $("#c-room_id").val('');
                $('#room').hide();
                $('#table').show();
            }

            $(document).on("change", "input[type=radio][name='row[type]']",
                function () {
                    var valType = $(this).val();
                    if (valType === 'qp') {

                        $("#c-table_id").val('');
                        $('#room').show();
                        $('#table').hide();

                        $("#c-room_id").data("params", function () {
                            return {custom: {shop_id: $("#c-shop_id").val()}};
                        });

                    } else {

                        $("#c-room_id").val('');
                        $('#room').hide();
                        $('#table').show();

                        $("#c-table_id").data("params", function () {
                            return {custom: {shop_id: $("#c-shop_id").val()}};
                        });
                    }
                });

            Controller.api.bindevent();
        },
        sync: function () {

            $('form').find(':submit').on('click', function (event) {
                // 处理提交逻辑
                event.preventDefault(); // 阻止表单默认提交行为
                var shopIdStr = $('#c-shop_id').val();
                if (shopIdStr === '') {
                    alert('店铺不能为空');
                    return false;
                }
                const items = shopIdStr.split(',');
                // const urlTemplate = '/api/shop/mt/syncCouponInfo?shop_id={id}';

                const urlTemplate = '/admin/coupon/mt/syncCouponInfo?shop_id={id}';

                // 定义一个异步函数用于处理每个元素
                async function handleItem(item) {
                    const url = urlTemplate.replace('{id}', item);
                    try {
                        const response = await fetch(url);
                        // console.log('response:' + JSON.stringify(response));
                        if (!response.ok) {
                            throw new Error('http状态错误: ${response.status}');
                        }
                        const data = await response.json();
                        if (data.code === 1) {
                            layer.msg('同步成功', {icon: 1});
                        }
                        if (data.code === 0) {
                            layer.msg('同步失败：' + data.msg, {icon: 2, time: 2000});
                        }
                        // console.log('请求体返回的值:', data);
                        layer.closeAll();
                    } catch (error) {
                        // console.log('请求报错，内容:', error);
                        layer.msg('同步失败：' + error, {icon: 2, time: 2000});
                    }
                    // 等待1秒
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }

                // 定义一个异步函数用于遍历数组
                async function processItems() {
                    for (const item of items) {
                        layer.msg(item + '：同步中...', {icon: 16, shade: 0.01, time: 10 * 1000});
                        await handleItem(item);
                    }
                }

                processItems();
            });

            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});